package top.ddandang.blog.service.impl;
import	java.util.HashMap;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import top.ddandang.blog.model.pojo.Statistics;
import top.ddandang.blog.mapper.StatisticsMapper;
import top.ddandang.blog.model.vo.StatisticVo;
import top.ddandang.blog.service.StatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.ddandang.blog.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author D
 * @since 2020-06-23
 */
@Service
@Slf4j
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, Statistics> implements StatisticsService {

    @Resource
    private StatisticsMapper statisticsMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 文章点击数量的key值
     */
    private final String hitsKey = "hits:";
    /**
     * 文章评论数量的key值
     */
    private final String commentAmountKey = "commentAmount:";
    /**
     * 总点击数量的key值
     */
    private final String totalHitsKey = "totalHits";
    /**
     * 总评论数量的key值
     */
    private final String totalCommentAmountKey = "totalCommentAmount";

    /**
     * 总文章数的key值
     */
    private final String totalArticleKey = "totalArticle";

    /**
     * 总用户数的key值
     */
    private final String totalUserKey = "totalUser";

    @Async
    @Override
    public void insertStatistics(Integer articleId) {

        Statistics statistics = new Statistics()
                .setArticleId(articleId);
        statisticsMapper.insert(statistics);
    }

    @Async
    @Override
    public void addRedisStatistics(Integer articleId) {
        redisUtil.incr(hitsKey+articleId, 1);
        redisUtil.incr(totalHitsKey, 1);
    }

    @Async
    @Override
    public void addRedisStatisticsComment(Integer articleId) {
        redisUtil.incr(commentAmountKey+articleId, 1);
        redisUtil.incr(totalCommentAmountKey, 1);
    }


    @Override
    public Map<String, Object> getStatisticsByArticleId(Integer articleId) {

        Map<String, Object> map = new HashMap<> ();
        int hits = 0;
        int commentAmount = 0;

        if(redisUtil.hasKey(hitsKey+articleId)) {
            hits = (int)redisUtil.get(hitsKey+articleId);
        }else if(redisUtil.hasKey(commentAmountKey+articleId)) {
            commentAmount = (int)redisUtil.get(commentAmountKey+articleId);
        }else {
            QueryWrapper<Statistics> queryWrapper = new QueryWrapper<Statistics>()
                    .eq("article_id", articleId);

            Statistics statistics = statisticsMapper.selectOne(queryWrapper);
            hits = statistics.getHits();
            commentAmount = statistics.getCommentAmount();
        }

        map.put("hits", hits);
        map.put("commentAmount", commentAmount);

        return map;
    }

    @Override
    public StatisticVo getTotalStatistics() {
        StatisticVo statisticVo = new StatisticVo();

        int totalHits = redisUtil.hasKey(totalHitsKey) ? (int) redisUtil.get(totalHitsKey) : statisticsMapper.getHitsAmount();
        redisUtil.set(totalHitsKey, totalHits);
        int totalCommentAmount = redisUtil.hasKey(totalCommentAmountKey) ? (int) redisUtil.get(totalCommentAmountKey) : statisticsMapper.getCommentAmount();
        redisUtil.set(totalCommentAmountKey, totalCommentAmount);


        int totalArticle = -1;
        if(redisUtil.hasKey(totalArticleKey)) {
            totalArticle = (int) redisUtil.get(totalArticleKey);
        }
        int totalUser = -1;
        if(redisUtil.hasKey(totalUserKey)) {
            totalUser = (int) redisUtil.get(totalUserKey);
        }
        statisticVo.setTotalArticle(totalArticle)
                .setTotalComment(totalCommentAmount)
                .setTotalUser(totalUser)
                .setTotalHits(totalHits);
        return statisticVo;
    }

    /**
     * 定时任务
     * 将缓存中的统计数据 加入到数据库中
     */
    @Scheduled(cron = "1 1 1/3 * * ?")
    public void updateDatabaseStatistic() {

        List<Integer> articleIdList = statisticsMapper.listArticleId();

        for(Integer id : articleIdList) {
            String keyHits = hitsKey + id;
            String keyCommentAmount = commentAmountKey + id;
            if(redisUtil.hasKey(keyHits)) {
                int hits = (int)redisUtil.get(keyHits);
                statisticsMapper.update(null, new UpdateWrapper<Statistics>()
                .eq("article_id", id)
                .set("hits", hits));
            }

            if(redisUtil.hasKey(keyCommentAmount)) {
                int commentAmount = (int)redisUtil.get(keyCommentAmount);
                statisticsMapper.update(null, new UpdateWrapper<Statistics>()
                        .eq("article_id", id)
                        .set("comment_amount", commentAmount));
            }
        }
    }

}
